package com.tianji.learning.mq;

import com.tianji.api.dto.remark.ChangedTimesDTO;
import com.tianji.common.utils.CollUtils;
import com.tianji.learning.service.IInteractionReplyService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

import static com.tianji.common.constants.MqConstants.Exchange.LIKE_RECORD_EXCHANGE;
import static com.tianji.common.constants.MqConstants.Key.QA_LIKED_TIMES_KEY;

/**
 * @author Covey
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class LikeTimesChangeListener {

    private final IInteractionReplyService replyService;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "qa.liked.times.queue", durable = "true"),
            exchange = @Exchange(name = LIKE_RECORD_EXCHANGE, type = ExchangeTypes.TOPIC),
            key = QA_LIKED_TIMES_KEY
    ))
    public void listenReplyLikedTimesChange(List<ChangedTimesDTO> changedTimesDTOs) {
        log.debug("监听到回答或评论的点赞数变更，数量：{}", changedTimesDTOs.size());
        if (CollUtils.isEmpty(changedTimesDTOs)) {
            return;
        }
        try {
            // 过滤掉变化量为0的记录
            List<ChangedTimesDTO> validChanges = changedTimesDTOs.stream()
                    .filter(dto -> dto.getChangedTimes() != 0)
                    .collect(Collectors.toList());
            if (CollUtils.isEmpty(validChanges)) {
                log.debug("没有有效的点赞数变更");
                return;
            }
            // 批量更新
            boolean success = replyService.updateBatchByBizId(validChanges);
            if (success) {
                log.debug("成功批量更新 {} 个回答/评论的点赞数", validChanges.size());
            } else {
                log.error("批量更新点赞数失败");
            }
        } catch (Exception e) {
            log.error("更新回答/评论点赞数失败", e);
        }
    }
}